var express = require('express');
var moment = require("moment");
var orm = require('orm');
var _ = require('underscore');

var log4js = require('log4js');
var logger = log4js.getLogger();

var router = express.Router();

router.get('/list', function(req, res, next) {
	var period = req.query.period;
	var timestamp = req.query.timestamp || Date.now();

	var map = {
		'week': function(st) {
			req.models.trade_guider_kpi_weekly.find({
				week_start: moment(new Date(parseInt(st))).isoWeekday("Monday").format('YYYY-MM-DD'),
    			week_end: moment(new Date(parseInt(st))).isoWeekday("Sunday").format('YYYY-MM-DD')
			}).all(function(err, results) {
				res.json({
					result: results,
					error: 0
				});
			})
		},

		'month': function (st) {
			req.models.trade_guider_kpi_monthly.find({
				create_month: moment(new Date(parseInt(st))).format('YYYY-MM')
			}).all(function(err, results) {
				res.json({
					result: results,
					error: 0
				});
			})
		}
	}

	var fn = map[period];

	if (_.isFunction(fn)) {
		fn(timestamp);
	} else {
		res.json({
			result: null,
			error: -100
		});
	}
});

module.exports = router;